<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;


/**
 * 新书书袋表
 * Class ArticleModel
 * @package app\common\model
 */
class BookHomeSchoolbag extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'book_home_schoolbag';

    /**
     * 书籍书袋关联
     */
    public function newBookSchoolbag()
    {
        return $this->belongsTo(ShopBook::class, 'book_id', 'id')
            ->select('book_name', 'author', 'press', 'pre_time', 'isbn', 'price', 'img', 'intro', 'shop_id');
    }

    /**
     * 判断是否加入书袋
     * @param book_id  书籍id
     * @param user_id  书籍id
     * @param $type  类型 1 新书   2 馆藏书
     * @param $barcode_id  条形码id 只有当 $type 为 2 才显示
     */
    public static function isSchoolbag($book_id, $user_id, $type = 1, $barcode_id = null)
    {
        if ($type == 2 && empty($barcode_id)) {
            return false;
        }
        return self::where('book_id', $book_id)
            ->where('user_id', $user_id)
            ->where('type', $type)
            ->where(function ($query) use ($barcode_id) {
                if (!empty($barcode_id)) {
                    $query->where('barcode_id', $barcode_id);
                }
            })
            ->first();
    }

    /**
     * 获取我的书包列表
     */
    public function myNewBookSchoolbagList($user_id)
    {
        $res = $this->from($this->getTable() . ' as ba')
            ->select('ba.id', 'ba.book_id', 'ba.create_time', 'b.book_name', 'b.author', 'b.press', 'b.pre_time', 'b.isbn', 'b.price', 'b.img', 'b.intro', 'b.shop_id')
            ->join('shop_book as b', 'b.id', '=', 'ba.book_id')
            ->join('shop as s', 's.id', '=', 'b.shop_id')
            ->where(function ($query) {
                $query->where('s.way', 1)->orWhere('s.way', 3);
            })
            ->where('ba.user_id', $user_id)
            ->where('ba.type', 1)
            ->orderByDesc('ba.id')
            ->get()
            ->toArray();
        return $res;
    }

    /**
     * 获取我的书包列表
     */
    public function myLibBookSchoolbagList($user_id, $limit = 10)
    {
        $res = $this->from($this->getTable() . ' as s')
            ->select('s.id', 's.create_time', 'b.id as book_id', 'b.book_name', 'b.author', 'b.isbn', 'b.press', 'b.pre_time', 'b.price', 'b.img', 'b.metaid', 'b.metatable', 's.barcode_id', 'c.barcode')
            ->join('lib_book as b', 'b.id', '=', 's.book_id')
            ->join('lib_book_barcode as c', 'c.id', '=', 's.barcode_id')
            ->where('s.user_id', $user_id)
            ->where('s.type', 2)
            ->orderByDesc('s.id')
            ->paginate($limit)
            ->toArray();

        return $res;
    }
}
